//
//  UDAlertView.m
//  UDPhone
//
//  Created by 115 on 14-2-12.
//  Copyright (c) 2014年 YLMF Co.,Inc. All rights reserved.
//

#import "Alert.h"

@interface Alert()

@property (nonatomic, strong) NSString *vcardString;

@end

@implementation Alert

- (nonnull id)initAlertController:(nonnull UIAlertController *)alertController {
    self = [super init];
    if (self) {
        _alertController = alertController;
    }
    return self;
}

+ (void)showViewCtrl:(UIViewController *)presentedCtrl {
        UITabBarController *tab = (UITabBarController *)[UIApplication sharedApplication].delegate.window.rootViewController;
        UIViewController *ctrl = tab;
        if ([tab isKindOfClass:[UITabBarController class]]) {
            ctrl = tab.selectedViewController;
        }
        UIViewController *fontCtrl = [self frontViewController:ctrl];
        [fontCtrl presentViewController:presentedCtrl animated:YES completion:nil];
    
}

+ (Alert *)showActionSheetWithTitle:(NSString *)title message:(NSString *)message dismissBlock:(UDAlertDidDisMissBlock)didMissBlock cancelButtonIndex:(NSInteger)index destructiveButtonIndex:(NSInteger)destructiveIndex titles:(NSArray<NSString *> *)titles {
    Alert *alert;
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleActionSheet];
    alert = [[Alert alloc] initAlertController:alertCtrl];
    for (int i = 0; i < titles.count; i++) {
        UIAlertActionStyle style = UIAlertActionStyleDefault;
        if (i == index) {
            style = UIAlertActionStyleCancel;
        }
        if (i == destructiveIndex) {
            style = UIAlertActionStyleDestructive;
        }
        UIAlertAction *action = [UIAlertAction actionWithTitle:titles[i] style:style handler:^(UIAlertAction *action) {
            if (didMissBlock) {
                didMissBlock(i);
            }
            [[AlertManager defaultManager] removeAlert:alert];
        }];
        [alertCtrl addAction:action];
    }
    [self showViewCtrl:alertCtrl];
//    alertCtrl.view.tintColor = [UIColor themeColor];
    
    [[AlertManager defaultManager] addAlert:alert];
    return alert;
}

+ (Alert *)showAlertViewWithTitle:(NSString *)title message:(NSString *)message dismissBlock:(UDAlertDidDisMissBlock)didMissBlock cancelButtonIndex:(NSInteger)index titles:(NSArray<NSString *> *)titles {
    return [self showAlertViewWithTitle:title message:message dismissBlock:didMissBlock cancelButtonIndex:index titles:titles configure:nil];
}

+ (nonnull Alert *)showAlertViewWithTitle:(nullable NSString *)title message:(nullable NSString *)message dismissBlock:(nullable UDAlertDidDisMissBlock)didMissBlock cancelButtonIndex:(NSInteger)index titles:(nonnull NSArray<NSString *> *)titles configure:(nullable void (^)( Alert * _Nullable )) configure {
    Alert *alert;
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    alert = [[Alert alloc] initAlertController:alertCtrl];
    alertCtrl.title = title;
    alertCtrl.message = message;
    for (int i = 0; i < titles.count; i++) {
        UIAlertActionStyle style = UIAlertActionStyleDefault;
        if (i == index) {
            style = UIAlertActionStyleCancel;
        }
        UIAlertAction *action = [UIAlertAction actionWithTitle:titles[i] style:style handler:^(UIAlertAction *action) {
            if (didMissBlock) {
                didMissBlock(i);
            }
            [[AlertManager defaultManager] removeAlert:alert];
        }];
        [alertCtrl addAction:action];
    }
    if (configure) {
        configure(alert);
    }
    [self showViewCtrl:alertCtrl];
    
    [[AlertManager defaultManager] addAlert:alert];
    return alert;
}

+ (UIViewController *)lastViewController {
    UIWindow *keyWindow = [[UIApplication sharedApplication] delegate].window;
    UITabBarController *tab = (UITabBarController *)keyWindow.rootViewController;
    UIViewController *ctrl = nil;
    if ([tab respondsToSelector:@selector(selectedViewController)]) {
        ctrl = tab.selectedViewController;
    } else {
        ctrl = tab;
    }
    UIViewController *fontCtrl = [self frontViewController:ctrl];
    return fontCtrl;
}

- (void)addTextFieldWithConfigurationHandler:(void (^ __nullable)( UITextField * _Nullable textField))configurationHandler {
    if (self.alertController) {
        [self.alertController addTextFieldWithConfigurationHandler:configurationHandler];
    }
}

- (void)cancelAction{
    [[Alert lastViewController] dismissViewControllerAnimated:YES completion:nil];
}

+ (UIViewController *)frontViewController:(UIViewController *)ctrl {
    while ([ctrl isKindOfClass:[UINavigationController class]] || ctrl.presentedViewController || [ctrl isKindOfClass:[UITabBarController class]]) {
        if (ctrl.presentedViewController) {
            ctrl = ctrl.presentedViewController;
        }
        if ([ctrl isKindOfClass:[UITabBarController class]]) {
            ctrl = ((UITabBarController *)ctrl).selectedViewController;
        }
        if ([ctrl isKindOfClass:[UINavigationController class]]) {
            ctrl = ((UINavigationController *)ctrl).viewControllers.lastObject;
        }
    }
    return ctrl;
}

@end

@interface AlertManager()

@property (nonatomic, strong) NSMutableArray<Alert *> *_availableAlerts;

@end

@implementation AlertManager

static AlertManager *_defaultManager;

- (instancetype)init
{
    self = [super init];
    if (self) {
        self._availableAlerts = [NSMutableArray array];
    }
    return self;
}

+ (AlertManager *)defaultManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _defaultManager = [[AlertManager alloc] init];
    });
    return _defaultManager;
}

- (NSArray<Alert *> *)availableAlerts {
    return [__availableAlerts copy];
}

- (void)addAlert:(Alert *)alert {
    [self._availableAlerts addObject:alert];
}

- (void)removeAlert:(Alert *)alert {
    [self._availableAlerts removeObject:alert];
}

/**
 移除所有的Alert
 */
- (void)removeAllAlerts {
    for (Alert *alert in self._availableAlerts) {
        __weak typeof (Alert) *weakAlert = alert;
        [alert.alertController dismissViewControllerAnimated:NO completion:^{
            [self removeAlert:weakAlert];
        }];
    }
}

@end
